#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;

class server
{
private:
    string server_ip;
    int server_port;
    int server_sockfd;
    vector<int> cfd;

public:
    server(string ip, int port);
    ~server();
    void run();
    static void RecvMsg(int conn);
};

server::server(string ip, int port) : server_ip(ip), server_port(port) {}

server::~server()
{
    for (auto tmp : cfd)
        close(tmp);
    close(server_sockfd);
}

void server::run()
{
    server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

    int optval = 1;
    setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));

    sockaddr_in server_socket;
    memset(&server_socket, 0, sizeof(server_socket));
    server_socket.sin_family = AF_INET;
    server_socket.sin_port = htons(server_port);
    server_socket.sin_addr.s_addr = inet_addr(server_ip.c_str());

    if (bind(server_sockfd, (sockaddr *)&server_socket, sizeof(server_socket)) == -1)
    {
        perror("bind");
        exit(1);
    }

    if (listen(server_sockfd, 20) == -1)
    {
        perror("listen");
        exit(1);
    }

    sockaddr_in client_addr;
    socklen_t length = sizeof(client_addr);

    while (1)
    {
        int conn = accept(server_sockfd, (sockaddr *)&client_addr, &length);
        if (conn < 0)
        {
            perror("connect");
            exit(1);
        }
        cout << "文件描述符为" << conn << "的客户端成功连接\n";
        cfd.push_back(conn);
        // 创建线程
        thread t(server::RecvMsg, conn);
        t.detach();

    }
}

void server::RecvMsg(int conn)
{
    char buffer[1000];
    while (1)
    {
        memset(buffer, 0, sizeof(buffer));
        int len = recv(conn, buffer, sizeof(buffer), 0);
        if (strcmp(buffer, "exit") == 0 || len <= 0)
            break;
        cout << "收到套接字描述符为" << conn << "发来的信息：" << buffer << endl;
    }
}

int main()
{
    server serv("127.0.0.1", 8888);
    serv.run();
}